package com.aabte.permissionframeworklearn.apacheshirodemo.contorller;

import com.aabte.permissionframeworklearn.apacheshirodemo.model.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * @author Daniel
 */
@Slf4j
@Controller
public class TestController {

    @GetMapping(value = "/login")
    public String login() {
        return "login";
    }

    @GetMapping(value = {"/index", "/"})
    public String index() {
        return "index";
    }

    @PostMapping(value = "/loginUser")
    public String loginUser(
            @RequestParam(value = "username") String username,
            @RequestParam(value = "password") String password,
            HttpSession session
    ) {
        log.info("Start loginUser. username: {}", username);
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);

        Subject subject = SecurityUtils.getSubject();

        String result = "login";
        try {
            subject.login(usernamePasswordToken);
            User user = (User) subject.getPrincipal();
            session.setAttribute("user", user);
            result = "index";
        } catch (AuthenticationException e) {
            log.info("User login failed. username: {}, ex: {}", username, e);
        }

        log.info("End loginUser. username: {}", username);
        return result;
    }

    @GetMapping(value = "/logout")
    public String logout() {
        log.info("Start logout.");
        Subject subject = SecurityUtils.getSubject();
        if (null != subject) {
            subject.logout();
        }
        log.info("End logout.");
        return "login";
    }

    @GetMapping(value = "/unauthorized")
    public String unauthorized() {
        return "unauthorized";
    }

    @GetMapping(value = "/admin")
    @ResponseBody
    public String admin() {
        return "admin success";
    }

    @GetMapping(value = "/edit")
    @ResponseBody
    public String edit() {
        return "edit success";
    }

}
